/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.view;

import com.aaron.platform.entity.FgysEnterprise;
import com.aaron.platform.entity.GczxOrderInfo;
import com.aaron.platform.entity.GczxPayDetail;
import com.aaron.platform.entity.GczxPaymentInfo;
import com.aaron.platform.exceptions.EnterpriseNotExistException;
import com.aaron.platform.service.IEnterpriseMgr;
import com.aaron.platform.service.IExcelTools;
import com.aaron.platform.service.IOrderMgr;
import com.aaron.platform.service.IPaymentMgr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author mac
 */
public class PaymentInfoBean extends DataListBean {

    private static Logger logger = Logger.getLogger(PaymentInfoBean.class);

    private IOrderMgr orderMgr;

    private IPaymentMgr paymentMgr;

    private IEnterpriseMgr enterpriseMgr;

    private IExcelTools excelTools;

    private List<SelectItem> payProList;

    private List<SelectItem> investIntList;

    private List<SelectItem> payTypeList;

    private List<SelectItem> enterPriseList;

    /** 目前的操作 1：view 2：new */
    private int currentOperation = 2;

    /** 录入的付款信息 */
    private GczxPaymentInfo paymentInfo;

    /** 是否可更新 */
    private boolean updatable;

        public PaymentInfoBean() {
        super();
        this.tableTitle = FacesUtil.getString("table_title_orderlist");

        // 删除、编辑、查看操作
        this.deletable = false;
        this.editable = false;
        this.viewable = false;

        //多选
        multiSelectable = false;

        paymentInfo = new GczxPaymentInfo();
        data = new ListDataModel();

    }

    public GczxPaymentInfo getPaymentInfo() {
        return paymentInfo;
    }

    public void init() {
        paymentInfo = new GczxPaymentInfo();
        data = new ListDataModel();
    }

    public void setPaymentInfo(GczxPaymentInfo paymentInfo) {
        this.paymentInfo = paymentInfo;
        if (paymentInfo.getPayDetails() != null) {
            this.data.setWrappedData(paymentInfo.getPayDetails());
        }
    }

    public boolean isUpdatable() {
        return updatable;
    }

    public void setUpdatable(boolean updatable) {
        this.updatable = updatable;
    }

    public void setOrderMgr(IOrderMgr orderMgr) {
        this.orderMgr = orderMgr;
    }

    public void setPaymentMgr(IPaymentMgr paymentMgr) {
        this.paymentMgr = paymentMgr;
    }

    public void setEnterpriseMgr(IEnterpriseMgr enterpriseMgr) {
        this.enterpriseMgr = enterpriseMgr;
    }

    public void setExcelTools(IExcelTools excelTools) {
        this.excelTools = excelTools;
    }

    @Override
    public void queryData() {

    }

    /**
     * 添加关联订单
     * @param orderInfos 订单列表
     */
    public void addData(List<GczxOrderInfo> orderInfos) {
        if (orderInfos == null) {
            return;
        }

        // 创建付款明细列表
        List<GczxPayDetail> payDetails = new ArrayList<GczxPayDetail>();
        for (GczxOrderInfo orderInfo : orderInfos) {
            GczxPayDetail payDetail = new GczxPayDetail();
            payDetail.setOrderInfo(orderInfo);
            payDetails.add(payDetail);
        }

        // 封装到data
        if (data.getWrappedData() == null) {
            this.data.setWrappedData(payDetails);
        } else {
            // 存放比较后无重复的列表
            List<GczxPayDetail> distictPayDetails = new ArrayList<GczxPayDetail>();

            // 比较是否有重复
            List<GczxPayDetail> payDetailList = (List<GczxPayDetail>) data.getWrappedData();
            boolean isOK;
            for (GczxPayDetail newPayDetail : payDetails) {
                isOK = true;
                for (GczxPayDetail existPayDetail : payDetailList) {
                    if (existPayDetail.getOrderInfo().equals(existPayDetail.getOrderInfo())) {
                        isOK = false;
                        break;
                    }
                }
                if (isOK == true) {
                    distictPayDetails.add(newPayDetail);
                }
            }
            // 新增付款信息到列表
            payDetailList.addAll(payDetails);
            //this.data.setWrappedData(payDetailList);
        }
        paymentInfo.setPayDetails((List<GczxPayDetail>) this.data.getWrappedData());
    }

    /**
     * 解除关联信息
     * @return
     */
    @Override
    public String deleteData() {
        int toDelIndex = data.getRowIndex();
        List<GczxPayDetail> gczxOrderInfos = (List<GczxPayDetail> )data.getWrappedData();
        gczxOrderInfos.get(toDelIndex).setPaymentInfo(null);
        gczxOrderInfos.remove(toDelIndex);
        //paymentInfo.setPayDetails(gczxOrderInfos);
        return null;
    }

    /** 只保存发票信息 */
    public String saveInvoiceOnly() {
        if (StringUtils.isBlank(paymentInfo.getInvoiceNo())) {
            FacesUtil.addErrorMessage(null, "er_invoice_no_required");
            return null;
        } else if (paymentInfo.getInvoiceValue() == 0) {
            FacesUtil.addErrorMessage(null, "er_invoice_value_required");
            return null;
        } else if (paymentInfo.getPayPro() == 0) {
            FacesUtil.addErrorMessage(null, "er_pro_type_required");
            return null;
        } else if (paymentInfo.getEnterpriseInfo().getEnterpriseId() == 0) {
            FacesUtil.addErrorMessage(null, "er_enterprise_name_required");
            return null;
        } else if (paymentInfo.getInvSubdate() == null) {
            FacesUtil.addErrorMessage(null, "er_submit_date_required");
            return null;
        } else if (paymentInfo.getPayType() == 0) {
            FacesUtil.addErrorMessage(null, "er_pay_type_required");
            return null;
        } else if (StringUtils.isBlank(paymentInfo.getPayRemarks())) {
            FacesUtil.addErrorMessage(null, "er_pay_remarks_required");
            return null;
        } else if (paymentInfo.getInvestInterface() == 0) {
            FacesUtil.addErrorMessage(null, "er_pay_invest_required");
            return null;
        }

        // 去除两端空格
        paymentInfo.setInvoiceNo(StringUtils.strip(paymentInfo.getInvoiceNo()));
        paymentInfo.setPayRemarks(StringUtils.strip(paymentInfo.getPayRemarks()));

        // 设置单位信息
        try {
            paymentInfo.setEnterpriseInfo(enterpriseMgr.findEnterpriseById(paymentInfo.getEnterpriseInfo().getEnterpriseId()));
        } catch (EnterpriseNotExistException ex) {
             FacesUtil.addErrorMessage(null, "er_enterprise_not_exist");
             return null;
        }

        // 保存付款信息
        paymentMgr.addOrUpdatePayInfo(paymentInfo);
        if (this.currentOperation == 2) {
           FacesUtil.addInfoMessage(null, "info_save_invoice_success", paymentInfo.getInvoiceNo());
        } else if (this.currentOperation == 1) {
           FacesUtil.addInfoMessage(null, "info_update_invoice_success", paymentInfo.getInvoiceNo());
        }
        
        return null;
    }

    /** 为当前付款项产生调差表 */
    public String genAdjustTable() {
        try {
            List<GczxPaymentInfo> paymentInfos = new ArrayList<GczxPaymentInfo>();
            paymentInfos.add(paymentInfo);
            excelTools.outputAdjustTable(paymentInfos);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(PaymentInfoBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BiffException ex) {
            java.util.logging.Logger.getLogger(PaymentInfoBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WriteException ex) {
            java.util.logging.Logger.getLogger(PaymentInfoBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            java.util.logging.Logger.getLogger(PaymentInfoBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /** 保存付款信息 */
    public String savePayment() {

        // 检验输入
        if (StringUtils.isBlank(paymentInfo.getInvoiceNo())) {
            FacesUtil.addErrorMessage(null, "er_invoice_no_required");
            return null;
        } else if (paymentInfo.getInvoiceValue() == 0) {
            FacesUtil.addErrorMessage(null, "er_invoice_value_required");
            return null;
        } else if (paymentInfo.getPayPro() == 0) {
            FacesUtil.addErrorMessage(null, "er_pro_type_required");
            return null;
        } else if (paymentInfo.getEnterpriseInfo().getEnterpriseId() == 0) {
            FacesUtil.addErrorMessage(null, "er_enterprise_name_required");
            return null;
        } else if (paymentInfo.getInvSubdate() == null) {
            FacesUtil.addErrorMessage(null, "er_submit_date_required");
            return null;
        } else if (paymentInfo.getPayType() == 0) {
            FacesUtil.addErrorMessage(null, "er_pay_type_required");
            return null;
        } else if (StringUtils.isBlank(paymentInfo.getPayRemarks())) {
            FacesUtil.addErrorMessage(null, "er_pay_remarks_required");
            return null;
        } else if (paymentInfo.getInvestInterface() == 0) {
            FacesUtil.addErrorMessage(null, "er_pay_invest_required");
            return null;
        }

        // 去除两端空格
        paymentInfo.setInvoiceNo(StringUtils.strip(paymentInfo.getInvoiceNo()));
        paymentInfo.setPayRemarks(StringUtils.strip(paymentInfo.getPayRemarks()));

        // 设置单位信息
        try {
            paymentInfo.setEnterpriseInfo(enterpriseMgr.findEnterpriseById(paymentInfo.getEnterpriseInfo().getEnterpriseId()));
        } catch (EnterpriseNotExistException ex) {
             FacesUtil.addErrorMessage(null, "er_enterprise_not_exist");
             return null;
        }

        // 检查订单付款信息：订单的所有付款金额<=发票金额
        double totalPay = 0;
        List<GczxPayDetail> payDetails = (List<GczxPayDetail>) data.getWrappedData();
        if (payDetails != null && !payDetails.isEmpty()) {
            for (GczxPayDetail payDetail : payDetails) {
                if (payDetail.getPayValue() <= 0) {
                    FacesUtil.addErrorMessage(null, "er_pay_value_less", payDetail.getOrderInfo().getOrderCode());
                    return null;
                }
                totalPay = totalPay + payDetail.getPayValue();

                // 设置与发票关联并产生付款说明
                payDetail.setPaymentInfo(paymentInfo);
                payDetail.setPayDetailHelp(genPayDetailHelp(payDetail));
            }
        }
        if (paymentInfo.getInvoiceValue() < totalPay) {
            FacesUtil.addErrorMessage(null, "er_pay_value_lt_invoice_value");
            return null;
        }
        // 订单的所有付款金额即为本次付款金额
        paymentInfo.setPayValue(totalPay);
        paymentInfo.setPayHelp(genPaymentHelp(paymentInfo));

        // 重新保存新的付款信息，并更新订单累积付款金额和审计金额）
//        paymentInfo.getPayDetails().clear();
//        paymentInfo.getPayDetails().addAll(payDetails);
        paymentMgr.addOrUpdatePayInfo(paymentInfo);
        if (paymentInfo.getPayDetails() != null) {
            for (GczxPayDetail payDetail : paymentInfo.getPayDetails()) {
                GczxOrderInfo orderInfo = orderMgr.findById(payDetail.getOrderInfo().getOrderId());
//                List<GczxPayDetail> payDetailsOfOrder = orderInfo.getPayDetails();
//                float payValueOfOrder = 0;
//                for (GczxPayDetail payDetailOfOrder : payDetailsOfOrder) {
//                    payValueOfOrder = payValueOfOrder + payDetailOfOrder.getPayValue();
//                }
//                orderInfo.setPayValue(payValueOfOrder);
                orderInfo.setAuditedValue(payDetail.getOrderInfo().getAuditedValue());
                
                // 设置订单状态
                if (orderInfo.getPayValue() != 0 && orderInfo.getPayValue() == orderInfo.getAuditedValue()) {
//                    payDetail.getOrderInfo().setOrderStatus(2);
                    orderInfo.setOrderStatus(2);
                } else {
//                    payDetail.getOrderInfo().setOrderStatus(1);
                    orderInfo.setOrderStatus(1);
                }
                orderMgr.updateOrderInfo(orderInfo);
            }
        }

        FacesUtil.addInfoMessage(null, "save_payment_info_success", paymentInfo.getInvoiceNo());
        return "payment_search";
    }

    /** 从明细返回 */
    public String toLastPage() {
        return "payment_search";
    }

    public String createNewPayment() {
        init();
        this.currentOperation = 2;
        return "payment_input";
    }

    /**
     * 产生总付款说明
     * @param paymentInfo
     * @return
     */
    private String genPaymentHelp(GczxPaymentInfo paymentInfo) {
        String contactCode = "";
        String enterpriseName = "";
        String firstProjectName = "";
        int projectSum = 0;
        List<GczxPayDetail> payDetails = paymentInfo.getPayDetails();
        if (payDetails != null && !payDetails.isEmpty()) {
            contactCode = payDetails.get(0).getOrderInfo().getContactCode();
            enterpriseName = payDetails.get(0).getOrderInfo().getEnterpriseInfo().getEnterpriseName();
            firstProjectName = payDetails.get(0).getOrderInfo().getTaskName();
            projectSum = payDetails.size();
        }
        if (projectSum > 1) {
            return FacesUtil.getString("help_payment_standard", contactCode, enterpriseName,
                firstProjectName, projectSum, paymentInfo.getPayType());
        }
        return FacesUtil.getString("help_payment_datail_standard", contactCode, enterpriseName,
                firstProjectName, paymentInfo.getPayType());
    }

    /**
     * 产生订单明细付款说明
     * @param paymentInfo
     * @return
     */
    private String genPayDetailHelp(GczxPayDetail payDetail) {
        String contactCode = "";
        String enterpriseName = "";
        String projectName = "";
        if (payDetail != null) {
            contactCode = payDetail.getOrderInfo().getContactCode();
            enterpriseName = payDetail.getOrderInfo().getEnterpriseInfo().getEnterpriseName();
            projectName = payDetail.getOrderInfo().getTaskName();
        }
        return FacesUtil.getString("help_payment_datail_standard", contactCode, enterpriseName,
                projectName, payDetail.getPaymentInfo().getPayType());
    }

    /**
     * 计算累计已付款金额
     * @return
     */
    private double calcLastTotalPay() {
        // 查找每条订单的所有付款信息
        double payValueOfOrder = 0;
        if (paymentInfo.getPayDetails() == null || paymentInfo.getPayDetails().size() <=1 ) {
            return payValueOfOrder;
        }
        for (GczxPayDetail payDetail : paymentInfo.getPayDetails()) {
            GczxOrderInfo orderInfo = orderMgr.findById(payDetail.getOrderInfo().getOrderId());
            List<GczxPayDetail> payDetailsOfOrder = orderInfo.getPayDetails();
            for (GczxPayDetail payDetailOfOrder : payDetailsOfOrder) {
                if (payDetailOfOrder.getPayDetailID() != payDetail.getPayDetailID()) {
                    payValueOfOrder = payValueOfOrder + payDetailOfOrder.getPayValue();
                }
            }
        }
        return payValueOfOrder;
    }

    /**
     * 获取所有订单付款总和
     * @return 订单付款综合
     */
    public String getTotalPayValue() {
        double totalPayValue = 0;
        List<GczxPayDetail> payDetails = (List<GczxPayDetail>) data.getWrappedData();
        if (payDetails != null) {
           for (GczxPayDetail payDetail : payDetails) {
                totalPayValue = totalPayValue + payDetail.getPayValue();
           }
        }
        return String.valueOf(totalPayValue);
    }

    /** 获取专业列表 */
    public List<SelectItem> getPayProList() {
        if (this.payProList == null) {
            payProList = new ArrayList<SelectItem>();
            payProList.add(new SelectItem(0, FacesUtil.getString("list_item_default")));
            payProList.add(new SelectItem(1, FacesUtil.getString("list_item_jz")));
            payProList.add(new SelectItem(2, FacesUtil.getString("list_item_cs")));
            payProList.add(new SelectItem(3, FacesUtil.getString("list_item_fgys")));
            payProList.add(new SelectItem(4, FacesUtil.getString("list_item_qyw")));
        }
        return payProList;
    }

    public List<SelectItem> getPayTypeList() {
        if (this.payTypeList == null) {
            payTypeList = new ArrayList<SelectItem>();
            payTypeList.add(new SelectItem(0, FacesUtil.getString("list_item_default")));
            payTypeList.add(new SelectItem(1, FacesUtil.getString("list_item_pay_gcsgf")));
            payTypeList.add(new SelectItem(2, FacesUtil.getString("list_item_pay_dlgcf")));
            payTypeList.add(new SelectItem(3, FacesUtil.getString("list_item_pay_zdf")));
            payTypeList.add(new SelectItem(4, FacesUtil.getString("list_item_pay_qjjsf")));
            payTypeList.add(new SelectItem(5, FacesUtil.getString("list_item_pay_gzf")));
            payTypeList.add(new SelectItem(6, FacesUtil.getString("list_item_pay_ttf")));
            payTypeList.add(new SelectItem(7, FacesUtil.getString("list_item_pay_jlf")));
            payTypeList.add(new SelectItem(8, FacesUtil.getString("list_item_pay_sjf")));
            payTypeList.add(new SelectItem(9, FacesUtil.getString("list_item_pay_kcf")));
            payTypeList.add(new SelectItem(10, FacesUtil.getString("list_item_pay_df")));
            payTypeList.add(new SelectItem(11, FacesUtil.getString("list_item_pay_zlf")));
        }
        return payTypeList;
    }

    /** 获取专业列表 */
    public List<SelectItem> getInvestIntList() {
        if (this.investIntList == null) {
            investIntList = new ArrayList<SelectItem>();
            investIntList.add(new SelectItem(0, FacesUtil.getString("list_item_default")));
            investIntList.add(new SelectItem(1, FacesUtil.getString("list_item_tz_sh_gc")));
            investIntList.add(new SelectItem(2, FacesUtil.getString("list_item_tz_sh_fy")));
            investIntList.add(new SelectItem(3, FacesUtil.getString("list_item_tz_jt")));
            investIntList.add(new SelectItem(4, FacesUtil.getString("list_item_tz_tt")));
        }
        return investIntList;
    }

    public List<SelectItem> getEnterpriseList() {
        if (this.enterPriseList == null) {
            enterPriseList = new ArrayList<SelectItem>();
            enterPriseList.add(new SelectItem(0, FacesUtil.getString("list_item_default")));
            List<FgysEnterprise> enterprises = enterpriseMgr.findAllEnterprises();
            for (FgysEnterprise enterprise : enterprises) {
                enterPriseList.add(new SelectItem(enterprise.getEnterpriseId(), enterprise.getEnterpriseName()));
            }
        }
        return enterPriseList;
    }

    public static Logger getLogger() {
        return logger;
    }

    public static void setLogger(Logger logger) {
        PaymentInfoBean.logger = logger;
    }

    @Override
    public void initColumnHeaders() {
        
    }

    @Override
    public String getColumnValue() {
        return null;
    }

    public int getCurrentOperation() {
        return currentOperation;
    }

    public void setCurrentOperation(int currentOperation) {
        this.currentOperation = currentOperation;
    }
}
